#include "Key_Tim.h"

static uint8_t key_state[KEY_NUM] = {0};
static uint16_t key_debounce[KEY_NUM] = {0};

void Key_Init(void) 
{
    GPIO_InitTypeDef GPIO_InitStruct;
    
    // 1. 使能GPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    
    // 2. 配置PA0-PA3为上拉输入（低电平有效）
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStruct);
}

void TIM3_KeyScan_Init(uint16_t prescaler, uint16_t period) 
{
    TIM_TimeBaseInitTypeDef TIM_InitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;
    
    // 1. 使能TIM3时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
    
    // 2. 配置TIM3定时器（示例：10ms中断）
    TIM_InitStruct.TIM_Prescaler = prescaler - 1;
    TIM_InitStruct.TIM_Period = period - 1;
    TIM_InitStruct.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM3, &TIM_InitStruct);
    
    // 3. 使能TIM3中断
    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
    NVIC_InitStruct.NVIC_IRQChannel = TIM3_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
    
    // 4. 启动定时器
    TIM_Cmd(TIM3, ENABLE);
}

// TIM3中断服务函数（需在stm32f10x_it.c中实现）
void TIM3_IRQHandler(void) 
{
    static const uint16_t key_pins[KEY_NUM] = {GPIO_Pin_3, GPIO_Pin_2, GPIO_Pin_1, GPIO_Pin_0};
    
    if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) 
	{
        for (uint8_t i = 0; i < KEY_NUM; i++) 
		{
            if (GPIO_ReadInputDataBit(GPIOA, key_pins[i]) == Bit_RESET) 
			{ // 检测低电平
                if (key_debounce[i] < KEY_DEBOUNCE_MS) 
				{
                    key_debounce[i]++;
                    if (key_debounce[i] == KEY_DEBOUNCE_MS) 
					{
                        key_state[i] = i + 1; // 消抖完成，记录按键编号(1-4)
                    }
                }
            } 
			else {
                key_debounce[i] = 0;
                key_state[i] = 0;
            }
        }
        TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
    }
}

uint8_t Key_GetPressed2(void) 
{
	for (uint8_t i = 0; i < KEY_NUM; i++) 
	{
		if (key_state[i] != 0) 
		{
			uint8_t pressed_key = key_state[i];
			key_state[i] = 0; // 读取后清零
			return pressed_key;
		}
}
    return 0; // 无按键按下
}
